﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public delegate void ProductNameClickEventHandler (object sender, EventArgs e);

    [Serializable]
    public partial class ProductListCtrl : BaseListControl, IListControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        public event ProductNameClickEventHandler ProductNameClick;

        protected void OnProductNameClick(EventArgs e)
        {
            if (ProductNameClick != null)
                ProductNameClick(this, e);
        }

        public Products ProductList
        {
            get { return (Products)SourceObject; }
            set { SourceObject = value; }
        }

        public String CategoryListSessionKey
        {
            get 
            {
                if(ViewState[ClientID + "_CategoryListSessionKey"] == null)
                    ViewState[ClientID + "_CategoryListSessionKey"] = Guid.NewGuid().ToString() + "_" + ClientID + "_category";
                return ViewState[ClientID + "_CategoryListSessionKey"].ToString();
            }
            set { ViewState[ClientID + "_CategoryListSessionKey"] = value; }
        }

        public Categories CategoryList
        {
            get
            {
                return Session[CategoryListSessionKey] == null ? null : (Categories)Session[CategoryListSessionKey];
            }
            set
            {
                Session[CategoryListSessionKey] = value;
            }
        }

        public Decimal GetTotal()
        {
            if (SourceObject == null)
                return 0;
            SourceObject.Rewind();
            decimal total = 0;
            for (int i = 0; i < SourceObject.RowCount; i++)
            {
                total += (int)SourceObject.GetColumn(Products.ColumnNames.Quantity) * (decimal)SourceObject.GetColumn(Products.ColumnNames.Cost);
                SourceObject.MoveNext();
            }

            return total;
        }

        bool allowViewDetail = false;

        public bool AllowViewDetails
        {
            get { return allowViewDetail; }
            set { allowViewDetail = value; }
        }

        protected void lnkProductName_OnClick(object sender, EventArgs e)
        {
            OnProductNameClick(e);
        }

        protected override void grid_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            string oldFilter ="";

            try
            {
                if (e.Item.ItemType == ListItemType.Footer)
                {
                    if(SessionUser.Purchase)
                        e.Item.Cells[11].Text = string.Format("{0:C}", GetTotal());
                }

                else if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
                {
                    if (CategoryList != null)
                    {
                        oldFilter = CategoryList.Filter;

                        Label lbl = e.Item.FindControl("lblCategory") as Label;
                        oldFilter = CategoryList.Filter;

                        CategoryList.Filter = Categories.ColumnNames.ID + "=" + e.Item.Cells[3].Text;
                        if(CategoryList.RowCount > 0)
                            lbl.Text = CategoryList.CategoryName;

                        CategoryList.Filter = oldFilter;
                    }
                }
            }
            catch (Exception ex)
            {
                CategoryList.Filter = oldFilter;
                ErrorLog.WriteToFile("ProductListCtrl.ascx.cs", "grid_OnItemDataBound", ex.StackTrace);
            }
        }

        #region IListControl Members

        public void DeleteCheckedItems()
        {
            String checkedItemID = "";
            for (int i = 0; i < grid.Items.Count; i++)
            {
                DataGridItem item = grid.Items[i];
                Control ctrl = item.FindControl("cbSelect");
                if (ctrl != null && ctrl is CheckBox && ((CheckBox)ctrl).Checked && ((CheckBox)ctrl).Attributes["ItemID"] != null)
                    checkedItemID += ((CheckBox)ctrl).Attributes["ItemID"].ToString() + ",";
            }
            if (checkedItemID != "")
                checkedItemID = checkedItemID.Remove(checkedItemID.Length - 1);
            checkedItemID = "(" + checkedItemID + ")";

            String oldFilter = Filter;
            if (!String.IsNullOrEmpty(oldFilter))
                Filter = Filter + " and (" + Products.ColumnNames.ID + " in " + checkedItemID + ")";
            else
                Filter = Products.ColumnNames.ID + " in " + checkedItemID;

            ProductList.Rewind();
            for (int i = 0; i < ProductList.RowCount; i++)
            {
                ProductList.Deleted = true;
                ProductList.LastModifiedByUser = SessionUser.ID;
                ProductList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                ProductList.MoveNext();
            }

            if (!SaveOnCommit)
                ProductList.Save();

            Filter = oldFilter;
        }

        public void DeleteSelectedItem()
        {
            throw new NotImplementedException();
        }

        public void AddNewItem(MyGeneration.dOOdads.SqlClientEntity newItem)
        {
            throw new NotImplementedException();
        }

        public void UpdateItem(MyGeneration.dOOdads.SqlClientEntity updatedItem)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}